import pymysql
import datetime
from redis import StrictRedis

# ---- 用pymysql 操作数据库
def get_connection():
    # conn = pymysql.connect(host=host, port=port, db=db, user=user, password=password)
    from persistence import sqlUtil
    db_name = 'kw_cpt_word'
    conn, cur = sqlUtil.get_cur(db_name)
    return conn
# ---- 加载数据库
def redis_init():
    redis = StrictRedis(host='localhost', port=6379, db=0, password='', decode_responses=True)
    return redis

redis = redis_init()

# 缓存加载数据库数据
def data_to_redis():
    # redis = redis_init()
    conn = get_connection() # 读取数据库数据
    cursor = conn.cursor(pymysql.cursors.DictCursor)
    cursor.execute("select * from keyword")
    data = cursor.fetchall()
    for row in data:
        id = row['id']
        word = row['word']
        updateTime = row['update_time']
        # print(id, word, updateTime)
        redis.set(word, str(id)+','+updateTime.strftime("%Y-%m-%d"))
    cursor.close()
    conn.close()
    # redis.close()

# 缓存数据写回数据库
def redis_to_data():
    # redis = redis_init()
    conn = get_connection() # 读取数据库数据
    cursor = conn.cursor(pymysql.cursors.DictCursor)
    for key in redis.keys():
        val = redis.get(key)
        arr = val.split(',')
        time = datetime.datetime.strptime(arr[1], '%Y-%m-%d').strftime('%Y-%m-%d')
        print(time)
        sql = "insert into keyword(id, word, update_time) VALUES("+arr[0]+',\''+key+'\',\''+arr[1]+"\')"
        print(sql)
        cursor.execute(sql)
    cursor.close()
    conn.close()
    # redis.close()

# 数据写入redis缓存
def insert_redis(id, word):
    redis.set(word, str(id)+','+datetime.datetime.now().strftime("%Y-%m-%d"))

if __name__ == '__main__':
    insert_redis(343243432, '1测试!')
    # print(datetime.datetime.now().strftime("%Y-%m-%d"))